package cn.amarone.wineblog.util;

import cn.amarone.wineblog.config.GlobalConfig;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.security.Key;
import java.util.Date;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * jwt工具类
 *
 * @author amarone
 * @create 2020-10-10 上午10:54
 */
@Component
public class JwtService {

  @Autowired private GlobalConfig globalConfig;

  public String createJWT(String id, String issuer, String subject, long ttlMillis) {

    // 对token 进行签名算法
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    // 使用自定义 apikey 签署 jwt
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(globalConfig.getAeskeyBase64());
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

    JwtBuilder builder =
        Jwts.builder()
            .setId(id)
            .setIssuedAt(now)// 签发时间
            // .setExpiration()
            .setSubject(subject)
            .setIssuer(issuer)// 签发者
            .signWith(signatureAlgorithm, signingKey);

    // if it has been specified, let's add the expiration
    if (ttlMillis > 0) {
      long expMillis = nowMillis + ttlMillis;
      Date exp = new Date(expMillis);
      builder.setExpiration(exp);
    }

    // Builds the JWT and serializes it to a compact, URL-safe string
    return builder.compact();
  }
}
